package com.handpay.zztong.hp.login.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.handpay.crypto.Caesar;
import com.handpay.framework.ClientEngine;
import com.handpay.framework.SecureManager;
import com.handpay.framework.swiper.SwiperDetectService;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.framework.utils.DES2PWD;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.base.callback.BusinessEngineListener;
import com.handpay.zztong.hp.base.service.CoreService;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.login.model.login.AccountLoginBean;
import com.handpay.zztong.hp.login.model.login.LoginModel;
import com.handpay.zztong.hp.login.model.login.LoginVerficationCodeBean;
import com.handpay.zztong.hp.login.widget.LoginTextItemView;
import com.handpay.zztong.hp.permission.PermissionRequestCode;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.ui.VerificationCodeView;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.utils.StatusBarUtil;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.Hashtable;
import java.util.List;

/**
 * 账账通使用
 *
 * @author ygchenN
 */
public class LoginActivity extends ZZTongActivity implements View.OnClickListener {

    private LoginTextItemView account_login_tv;
    private LoginTextItemView password_login_tv;
    private VerificationCodeView mVerificationCodeView;
    private ProgressBar mVerificationCodeprogressBar;
    private EditText et_verification_code;
    private CheckBox mRemenberPwd;
    private boolean isUseVerificationCode = false;
    private LoginModel mLoginModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.setContentView(R.layout.activity_login);
        mLoginModel = new LoginModel();

        //防止截屏
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        // 启动SwiperDetectService.这个监听一直存在。不取消
        this.startService(new Intent(this, SwiperDetectService.class));
        super.onCreate(savedInstanceState);
        StatusBarUtil.setTranslucent(this,0);
        initPermission();
        account_login_tv = (LoginTextItemView) findViewById(R.id.account_tv);
        password_login_tv = (LoginTextItemView) findViewById(R.id.textview_pwd);
        mVerificationCodeView = (VerificationCodeView) findViewById(R.id.verification_code_view);
        mVerificationCodeprogressBar = (ProgressBar) findViewById(R.id.verification_code_progress_bar);
        mVerificationCodeView.setOnClickListener(this);
        et_verification_code = (EditText) findViewById(R.id.et_verification_code);
        TextView tv_login_version = (TextView) findViewById(R.id.tv_login_version);
        tv_login_version.setText(String.format("%s%s", getString(R.string.tv_version), ClientEngine.VERSION));
        mRemenberPwd = (CheckBox) findViewById(R.id.remember_pwd_cb);
        mRemenberPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                AccountUtils.saveSelectRemenberCheck(isChecked);
            }
        });
        mRemenberPwd.setChecked(AccountUtils.getSelectRemenberCheck() == null || Boolean.parseBoolean(AccountUtils.getSelectRemenberCheck().toString()));
        Button mLoginBtn = (Button) findViewById(R.id.button_login);
        Button mRegisterBtn = (Button) findViewById(R.id.button_register);
        findViewById(R.id.button_forgetpwd).setOnClickListener(this);
        mLoginBtn.setOnClickListener(this);
        mRegisterBtn.setOnClickListener(this);
        mIsMainPage = true;
        Intent intent = new Intent(LoginActivity.this, CoreService.class);
        stopService(intent);
        mLoginBtn.setOnLongClickListener(new OnLongClickListener() {

            @Override
            public boolean onLongClick(View arg0) {
                if (ZZTConfig.isTestLocation) {
                    setLocation("百度定位的地址", false);
                }
                return false;
            }
        });
        mRegisterBtn.setOnLongClickListener(new OnLongClickListener() {

            @Override
            public boolean onLongClick(View arg0) {
                if (ZZTConfig.isTestSelectLocation) {
                    setLocation("允许范围的中心坐标", true);
                }
                return false;
            }
        });

        String accountName = AccountUtils.getRMSAccountName();
        if (!TextUtils.isEmpty(accountName)) {
            account_login_tv.setText(accountName);
        }
        if (isUseVerificationCode) {
            getVerificationCode();
        } else {
            findViewById(R.id.verification_code_view_ll).setVisibility(View.GONE);
        }
//        account_login_tv.setText("ssx001");
//        password_login_tv.setText("aaa111");
//        account_login_tv.setText("liuru713");
//        password_login_tv.setText("liuru713");

//        account_login_tv.setText("yang001");
//        password_login_tv.setText("111aaa");
    }

    @Override
    public void onSucceed(int requestCode, List<String> grantPermissions) {
        if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_READ_PHONE_STATE_AND_STORAGE) {
            HPLog.d(HPLog.SSX_TAG, grantPermissions.toString());
            Toast.makeText(this, R.string.message_storage_and_phonestate_succesed, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取权限
     */
    private void initPermission() {
        if (!AndPermission.hasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE)) {
            Toast.makeText(this, R.string.message_storage_and_phonestate_failed, Toast.LENGTH_SHORT).show();
            AndPermission.with(this).requestCode(PermissionRequestCode.REQUEST_CODE_PERMISSION_READ_PHONE_STATE_AND_STORAGE).
                    permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE).
                    rationale(new RationaleListener() {
                        @Override
                        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                            AndPermission.rationaleDialog(LoginActivity.this, rationale).show();
                        }
                    }).send();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_READ_PHONE_STATE_AND_STORAGE) {
            initPermission();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (AccountUtils.getRMSAccountPwd() != null && AccountUtils.getRMSAccountPwd().length() > 0) {
                String beforePwd = DES2PWD.decryptDES(AccountUtils.getRMSAccountPwd(), ZZTConfig.SECRETKEY);
                String afterPwd = Caesar.caesarDeciphering(beforePwd);
                password_login_tv.setText(afterPwd);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取验证码
     **/
    private void getVerificationCode() {
        mVerificationCodeprogressBar.setVisibility(View.VISIBLE);
        mVerificationCodeView.setVisibility(View.INVISIBLE);
        Hashtable<String, String> params = new Hashtable<>();
        if (isUseVerificationCode) {
//            doJsonPost(true, this, Do_GetLoginVerificationCode, LoginVerficationCodeBean.class, params, false);
            mLoginModel.doGetLoginVerificationCodePost(this, params, new BusinessEngineListener<LoginVerficationCodeBean>() {
                @Override
                public void callbackBusinessResponse(LoginVerficationCodeBean bean) {
                    String code = bean.getVerifiCode();
                    code = SecureManager.getInstance().des(code, 0, null);
                    if (!TextUtils.isEmpty(code)) {
                        updateLocalVerificationCode(code);
                    }
                    mVerificationCodeprogressBar.setVisibility(View.INVISIBLE);
                    mVerificationCodeView.setVisibility(View.VISIBLE);
                }
            });
        }
    }


    /***
     * 登录操作
     */
    public void doLogin() {
        String accountString = account_login_tv.getText().toString();
        String pwdString = password_login_tv.getText().toString();
        Editable code = et_verification_code.getText();
        if (TextUtils.isEmpty(accountString)) {
            Toast.makeText(this, R.string.no_input_account, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(pwdString)) {
            Toast.makeText(this, R.string.no_input_password, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!AccountUtils.isPWDLegal(pwdString,6)) {
            Toast.makeText(this, R.string.illegal_input_password, Toast.LENGTH_SHORT).show();
            return;
        }
        Hashtable<String, String> params = new Hashtable<>();
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(accountString, 1, null));
        params.put("pwd", SecureManager.getInstance().des(pwdString, 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        if (isUseVerificationCode) {
            if ((TextUtils.isEmpty(code.toString()) || !mVerificationCodeView.validateCode(code.toString()))) {
                Toast.makeText(this, R.string.error_verifivcation, Toast.LENGTH_SHORT).show();
                //需要重新到后台获取一次验证码
                return;
            }
            if (!TextUtils.isEmpty(code.toString())) {
                params.put("verifiCode", SecureManager.getInstance().des(code.toString().trim(), 1, null));
            }
        }
        if (!AndPermission.hasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE)) {
            Toast.makeText(this, R.string.message_storage_and_phonestate_failed, Toast.LENGTH_SHORT).show();
            AndPermission.with(this).requestCode(PermissionRequestCode.REQUEST_CODE_PERMISSION_READ_PHONE_STATE_AND_STORAGE).
                    permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE).
                    rationale(new RationaleListener() {
                        @Override
                        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                            AndPermission.rationaleDialog(LoginActivity.this, rationale).show();
                        }
                    }).send();
            return;
        }
        mLoginModel.doAccountLoginPost(this, params, new BusinessEngineListener<AccountLoginBean>() {
            @Override
            public void callbackBusinessResponse(AccountLoginBean bean) {
                String userId = SecureManager.getInstance().des(CommonUtils.objectToString(bean.getUserID()), 0, null);
                AccountUtils.saveAccount(LoginActivity.this, bean.getAccount(), bean.getPhone(), AccountUtils.convertStatus(bean.getStatus()), bean.getFailDescription(), bean.getMerchantCode(), userId);
                String accountString = account_login_tv != null ? account_login_tv.getText().toString() : "";
                if (accountString.length() > 0) {
                    AccountUtils.saveRMSAccountName(accountString);
                } else {
                    AccountUtils.saveRMSAccountName(bean.getAccount());
                }

                if (mRemenberPwd.isChecked()) {
                    try {
                        String beforePwd = password_login_tv.getText().toString().trim();
                        String afterPwd = Caesar.caesarEncryption(beforePwd);
                        AccountUtils.saveRMSAccountPWD(DES2PWD.encryptDES(afterPwd, ZZTConfig.SECRETKEY));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    AccountUtils.removeRMSPWDData();
                }
                AccountUtils.setShopName(LoginActivity.this, bean.getShopName());
                onFunctionTab(null);
                finish();
            }
        });
    }

    private void updateLocalVerificationCode(String code) {
        if (mVerificationCodeView != null) {
            et_verification_code.setText("");
            mVerificationCodeView.updateChar(code);
        }
    }

    @Override
    public void onClick(View v) {
//        boolean isCheckedVersion = (Boolean) ClientEngine.getInstance().getGlobal(ZZTongActivity.VerifyVersionOK, false);
        int i = v.getId();
        if (i == R.id.button_login) {

//            if (isCheckedVersion) {
            doLogin();
//            } else {
//                if (doVerifyVersion(this)) {
//                    mNext = new Runnable() {
//                        @Override
//                        public void run() {
//                            doLogin();
//                        }
//                    };
//                }
//            }

        } else if (i == R.id.button_register) {
            goToRegister();

        } else if (i == R.id.button_forgetpwd) {
            goToFindPassword();

        } else if (i == R.id.verification_code_view) {
            getVerificationCode();
        }
    }

    private void goToRegister() {
        Intent register = new Intent(this, RegisterActivity.class);
        this.startActivity(register);
    }

    private void goToFindPassword() {
        Intent intent = new Intent(this, FindPwdActivity.class);
        this.startActivity(intent);
    }

    @Override
    protected boolean isShownTabs() {
        return false;
    }

    @Override
    public ActionBar getActivityActionBar() {
        return new ActionBar(getString(R.string.newLoginTitle));
    }

    @Override
    protected boolean isShownTopBar() {
        return false;
    }

    private AlertDialog dialog;

    public void setLocation(String title, final boolean isAddress) {
        if (dialog != null && dialog.isShowing()) {
            return;
        }
        AlertDialog.Builder ab = new AlertDialog.Builder(this);
        LayoutInflater li = LayoutInflater.from(this);
        View content = li.inflate(R.layout.setting_location, null);
        TextView tvTitle = (TextView) content.findViewById(R.id.addressTitle);
        tvTitle.setText(title);
        final EditText etLatitude = (EditText) content.findViewById(R.id.et_latitude);
        final EditText etLongTitude = (EditText) content.findViewById(R.id.et_longtitude);
        final EditText etLocation = (EditText) content.findViewById(R.id.et_location);
        ab.setView(content);
        ab.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String latitude = etLatitude.getText().toString();
                String longTitude = etLongTitude.getText().toString();
                String location = etLocation.getText().toString();
                HPLog.e("fdl", "address:ZZTongActivity.isTestLocation");
                if (TextUtils.isEmpty(latitude) || TextUtils.isEmpty(longTitude) || TextUtils.isEmpty(location)) {
                    return;
                }
                if (isAddress) {
                    ClientEngine.getInstance().saveGlobal(BaseProtocolKey.KEY_TEST_SELECT_LATITUDE, Double.parseDouble(latitude));
                    ClientEngine.getInstance().saveGlobal(BaseProtocolKey.KEY_TEST_SELECT_LONGTITUDE, Double.parseDouble(longTitude));
                } else {
                    ClientEngine.getInstance().saveGlobal(BaseProtocolKey.KEY_TEST_LATITUDE, Double.parseDouble(latitude));
                    ClientEngine.getInstance().saveGlobal(BaseProtocolKey.KEY_TEST_LONGTITUDE, Double.parseDouble(longTitude));
                    ClientEngine.getInstance().saveGlobal(BaseProtocolKey.KEY_TEST_ADDRESS, location);
                }

            }
        });
        ab.setCancelable(false);
        dialog = ab.create();
        dialog.show();
    }
}
